<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Mobile\Controller;

use Think\Controller;

/**
 * Description of PrizeController
 *
 * @author asus
 */
class PrizeController extends \Mobile\Controller\BaseController {

    private $appid, $secret;

    public function __construct() {
        parent::__construct();
        $this->appid = 'wxb493f754ce9c0e03';
        $this->secret = '03f5bd902f45a37b6ad1b2eaceffd75d';
    }

    //put your code here
    public function index() {
        //$this->user();
//        print_r($_GET);
//        return;
        if ($_GET['flag'] == 'rule') {
            $this->rule();
            return;
        }
        if ($_GET['flag'] == 'getCode') {
            $time = I('time');
            if(time()-$time>1800){
                echo json_encode(array(-1,'time out'));
                return;
            }
            $pk189 = md5('qw12fg' . $time);
            if(I('pk189')!=$pk189){
                echo json_encode(array(-1,'check error'));
                return;
            }
            $d = $this->getcode();
            //echo json_encode(array('code' => $d[0], 'msg' => $d[1]));
            echo json_encode($d);
            return;
        }
        if (!isset($_GET['pk189'])) {
            header('Location: http://www.189pk.com/huizelong/index?id=' . rawurlencode($_GET['id']) . '&fcode=' . rawurlencode($_GET['code']));
            return;
        }
        //if ($id) {
        $this->assign('id', $_GET['id']);
        $this->assign('code', $_GET['code']);
        $this->display();
    }

    public function user() {
        if (session('weixinname') && session('weixinname') != '') {
            return true;
        }

        if (isset($_GET['state']) && isset($_GET['code'])) {
            $this->weiuser($_GET['code']);
            return true;
        }
        $returnurl = 'http://www.hzlwine.com/Mobile/Prize/code?id=' . $_GET['id'] . '&fcode=' . $_GET['code'];
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=' . rawurlencode($returnurl) . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header('Location: ' . $url);
    }

    /**
     * 
     * @param type $code
     * @return type "openid":" OPENID",  
      " nickname": NICKNAME,
      "sex":"1",
      "province":"PROVINCE"
      "city":"CITY",
      "country":"COUNTRY",
      "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
      "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
      "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
     */
    private function weiuser($code) {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->secret . '&code=' . $code . '&grant_type=authorization_code';
        $d = file_get_contents($url);
        $darr = json_decode($d, TRUE);
        $access_token = isset($darr['access_token']) ? $darr['access_token'] : '';
        $openid = isset($darr['openid']) ? $darr['openid'] : '';
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $d = file_get_contents($url);
        $darr = json_decode($d, TRUE);
        session('weixinname', $darr);
        return $darr;
    }

    private function curlget($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch); //释放curl句柄
        return $output;
    }

    public function code() {
        $this->display();
    }

    public function rule() {
        $this->display('rule');
    }

    private function getcode() {
        $id = authcode($_GET['id'], 'DECODE');
        if (!$id) {
            return array(-2, 'error param');
        }
        $data = D('actcode')->where(array('id' => $id))->find();
        $act_id = isset($data['act_id']) ? intval($data['act_id']) : 0;
        $check_code = isset($data['check_code']) ? trim($data['check_code']) : '';
        if ($check_code != $_GET['code']) {
            return array(-1, 'error--'.$check_code.'='.$_GET['code']);
        }
        if ($data['prize_code'] > 0) {
            return array(-2, 'has get');
        }
        $data = D('actdetail')->where(array('act_id' => $act_id))->select();
        $num = rand(1, 100000000);
        $prize_probability = 0;
        foreach ($data as $v) {
            if ($num > $prize_probability && $num <= ($v['prize_probability'] + $prize_probability)) {
                if (is_array($v) && !empty($v)) {
                    $arr = session('weixinname');
                    D('actcode')->where(array('id' => $id))->save(array('prize_code' => $v['id'], 'prize_money' => $v['prize_money'], 'prize_time' => time(), 'open_id' => $_GET['open_id'], 'user_info' => json_encode($arr)));
                    return array(1, $v['prize_money']);
                }
            }
            $prize_probability += $v['prize_probability'];
        }
        return array(-5, 'error');
    }

}
